﻿using APISDKDemo.Common;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace APISDKDemo.Service
{
    /// <summary>
    /// HttpClientFactory Demo
    /// </summary>
    public class SampleClient : ISampleClient
    {
        private readonly HttpClient _client;

        private readonly APIConfig _apiConfig;

        public SampleClient(HttpClient client, IOptions<APIConfig> options)
        {
            _client = client;
            _apiConfig = options.Value;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url">要请求的地址</param>
        /// <param name="queryStringData">querystring参数键值对</param>
        /// <returns></returns>
        public async Task<SDKResult> GetAsync(string url, IDictionary<string, string> queryStringData)
        {
            if (queryStringData == null)
            {
                throw new ArgumentNullException("queryStringData不能为null");
            }

            var qsItems = queryStringData.OrderBy(o => o.Key).Select(kv => kv.Key + "=" + kv.Value);

            string queryString = string.Join("&", qsItems);

            string sign = EncryptExtension.MD5Hash(queryString + _apiConfig.AppSecret);

            SDKResult sdkClient = new SDKResult();

            _client.DefaultRequestHeaders.Add("sign", sign);
            var resp = await _client.GetAsync(url + "?" + queryString);


            sdkClient.Result = await resp.Content.ReadAsStringAsync();
            sdkClient.StatusCode = resp.StatusCode;

            return sdkClient;

        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="queryStringData"></param>
        /// <returns></returns>
        public async Task<SDKResult> PostAsync(string url, IDictionary<string, string> formStringData)
        {
            if (formStringData == null)
            {
                throw new ArgumentException("formStringData不能为null");
            }

            var qsItems = formStringData.OrderBy(o => o.Key).Select(kv => kv.Key + "=" + kv.Value);

            string formString = string.Join("&", qsItems);

            string sign = EncryptExtension.MD5Hash(formString + _apiConfig.AppSecret);

            _client.DefaultRequestHeaders.Add("sign", sign);
            var resp = await _client.PostAsync(url, new FormUrlEncodedContent(formStringData));

            SDKResult sdkResult = new SDKResult();
            sdkResult.StatusCode = resp.StatusCode;
            sdkResult.Result = await resp.Content.ReadAsStringAsync();

            return sdkResult;

        }
    }
}
